package account_manage

import (
	"fmt"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/layout"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
	"github.com/atotto/clipboard"
	"go_gui/diy"
	"go_gui/g"
	"go_gui/lib"
	"strings"
	"time"
)

// FindMongoView mongo数据查询
func FindMongoView() {
	// 结果显示
	_showInfo := widget.NewMultiLineEntry()
	_dataTable := widget.NewList(
		func() int {
			return 0
		},
		func() fyne.CanvasObject {
			return widget.NewLabel("data-temp")
		},
		func(id widget.ListItemID, item fyne.CanvasObject) {
		},
	)

	// 数据表选择
	_showTableList := []string{
		"userinfo",
		"hero",
		"itemlist",
	}
	_mdbTableList := g.Mdb.GetTableList()
	for _, table := range _mdbTableList {
		if lib.InSlice(table, _showTableList) {
			continue
		}
		_showTableList = append(_showTableList, table)
	}
	_tableSelect := widget.NewSelect(_showTableList, nil)
	_tableSelect.SetSelectedIndex(0)

	// mongo 操作选择
	_actSelect := widget.NewSelect([]string{"Find", "Count"}, nil)
	_actSelect.SetSelectedIndex(0)

	// 查询条件
	_whereEntry := &widget.Entry{
		Wrapping:    fyne.TextWrapOff,
		PlaceHolder: "查询条件  例：{\"uid\": \"xxxxxxxxxxxx\"}               ",
	}

	// 查询按钮
	_findFunc := func() {
		if IsNoServer() {
			diy.ShowSleepInfor(1, "无区服信息!")
			return
		}

		_where := _whereEntry.Text
		if _where == "" {
			diy.ShowInformation("请输入查询条件", _whereEntry)
			return
		}
		_resWhere := make(map[string]any)
		err := lib.Loads([]byte(_where), &_resWhere)
		if err != nil {
			diy.ShowInformation("条件格式有误!请检查", _whereEntry)
			return
		}

		// 清空结果拦
		_showInfo.Text = ""
		_showInfo.Refresh()

		_table := _tableSelect.Selected
		switch _actSelect.Selected {
		case "Find":
			_dataList := g.Mdb.Find(_table, _resWhere)
			_dataLen := len(_dataList)
			if _dataLen <= 0 {
				diy.ShowSleepInfor(1, "暂无数据!")
				return
			}

			_dataTable.OnSelected = func(id widget.ListItemID) {
				_showInfo.Text = lib.DefaultMarshalIndent(_dataList[id])
				_showInfo.Refresh()
			}

			// 显示的表头
			_showKeys := []string{"uid"}
			for key := range _dataList[0] {
				if lib.InSlice(key, _showKeys) {
					continue
				}
				_showKeys = append(_showKeys, key)
			}
			_dataStrList := make([]string, len(_dataList))
			for idx, data := range _dataList {
				var _dataStr string
				for _, k := range _showKeys {
					_dataStr += fmt.Sprintf(" %s:%v", k, data[k])
					_dataStrList[idx] = _dataStr
				}
			}
			_dataTable.Length = func() int {
				return _dataLen
			}

			_dataTable.CreateItem = func() fyne.CanvasObject {
				return container.NewHBox(
					container.NewHBox(
						widget.NewIcon(theme.HomeIcon()),
						widget.NewLabel("data-num"),
					),
					widget.NewLabel("data-temp"),
				)
			}

			_dataTable.UpdateItem = func(id widget.ListItemID, item fyne.CanvasObject) {
				_numStr := g.C.IntToString(id + 1)
				_numStrLen := len(_numStr)
				_defaultSpaceNum := 4
				for i := 0; i <= _defaultSpaceNum-_numStrLen; i++ {
					_numStr += " "
				}

				_item := item.(*fyne.Container)
				_item.Objects[0].(*fyne.Container).Objects[1].(*widget.Label).SetText(fmt.Sprintf("%s", _numStr))
				_item.Objects[1].(*widget.Label).SetText(_dataStrList[id])
			}

			_dataTable.Refresh()
			diy.ShowSleepInfor(1, "SUCCESS!")
		case "Count":
			_dataTable.Length = func() int {
				return 0
			}
			_dataTable.Refresh()

			_res := g.Mdb.Count(_table, _resWhere)
			_showInfo.Text = g.C.Int64ToString(_res)
			_showInfo.Refresh()
		}
	}
	_findButton := widget.NewButton("查询", _findFunc)
	_whereEntry.OnSubmitted = func(s string) {
		_findFunc()
	}

	_selectInfo := container.NewVBox(
		widget.NewSeparator(),
		container.NewHBox(
			widget.NewLabel("表名"),
			_tableSelect,
			_actSelect,
			_whereEntry,
		),
		container.NewGridWithColumns(3, layout.NewSpacer(), _findButton, layout.NewSpacer()),
	)

	_showUi := container.NewHSplit(_dataTable, _showInfo)
	_showUi.Offset = 0.65
	view := container.NewBorder(
		nil, _selectInfo, nil, nil,
		_showUi,
	)

	w := fyne.CurrentApp().NewWindow(fmt.Sprintf("数据库查询-%s:%s", CurServerInfo.DbHost, CurServerInfo.DbName))
	w.SetContent(view)
	w.CenterOnScreen()
	w.Resize(fyne.NewSize(1200, 600))
	w.Show()

}

// _chkAppendMenuItems 添加可选操作
func _chkAppendMenuItems(setKey, setVal string, cell fyne.CanvasObject) []*fyne.MenuItem {
	menuItems := make([]*fyne.MenuItem, 0)
	if lib.InSlice(setKey, []string{"uid"}) {
		menuItems = append(
			menuItems,
			fyne.NewMenuItem("Copy", func() {
				clipboard.WriteAll(setVal)
				_msg := fmt.Sprintf("骚年!!!!!\n恭喜你，Copy成功~~~\nCopyKey: %s\nCopyValue: %s", setKey, setVal)
				diy.ShowLabelInfo(_msg, cell, time.Second*2)
			},
			),
		)
	}
	switch setKey {
	case "uid":
		// 非内网才有这个选项
		if !strings.Contains(CurServerInfo.DbHost, "10.0.0.") {
			menuItems = append(menuItems, fyne.NewMenuItem("复制该账号到内网", func() {
				CopyUser(setVal)
			}))
		}
		menuItems = append(menuItems, fyne.NewMenuItem("查询玩家信息", func() {
			ShowUserInfoView(setVal)
		}))
	}
	return menuItems
}
